﻿using Entitas;

public class RecordSystem : IExecuteSystem, ITearDownSystem
{
    private readonly IExportRecordService _exportRecordService;

    public RecordSystem(IExportRecordService exportRecordService)
    {
        if (!Contexts.sharedInstance.game.recordGlobal.recordMode &&
            Contexts.sharedInstance.game.recordGlobal.replayMode)
        {
            return;
        }

        _exportRecordService = exportRecordService;
    }


    public void Execute()
    {
        if (_exportRecordService == null)
        {
            return;
        }

        var entities = Contexts.sharedInstance.game.GetGroup(GameMatcher.AllOf(GameMatcher.Record, GameMatcher.Input))
            .GetEntities();

        foreach (var e in entities)
        {
            RecordComponent r = e.record;
            InputComponent i = e.input;
            r.inputOps.Add(i.inputOp);
        }
    }

    public void TearDown()
    {
        if (_exportRecordService == null)
        {
            return;
        }

        var entities = Contexts.sharedInstance.game.GetGroup(GameMatcher.Record)
            .GetEntities();

        _exportRecordService.Start(Contexts.sharedInstance.game.recordGlobal.recordPath);
        foreach (var e in entities)
        {
            RecordComponent r = e.record;
            _exportRecordService.Export(r.inputId, r.inputOps);
        }

        _exportRecordService.End();
    }
}